import numpy as np
import pandas as pd
import torch
from matplotlib import pyplot as plt
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import LSTM
from tensorflow.keras.layers import Dense, Dropout
from sklearn.preprocessing import MinMaxScaler
from tensorflow.keras.wrappers.scikit_learn import KerasRegressor
from sklearn.model_selection import GridSearchCV
from sklearn.model_selection import GridSearchCV, KFold

# 读入数据，将第一列设置为index和时间类型
df=pd.read_excel("positive.xlsx",parse_dates=["Detection Date"])
# print(df.head())
# print(df.tail())
# print(df.shape)
df=np.array(df)
# df=df.tolist()
datalen=len(df)
data=df
# 进行缩放
scaler = MinMaxScaler(feature_range=(0,1))
df = scaler.fit_transform(df)

# 转换格式
def createXY(dataset,n_past):
    dataX = []
    dataY = []
    for i in range(n_past, len(dataset)):
            if i+5<=len(dataset):
                dataX.append(dataset[i - n_past:i, 0:dataset.shape[1]])
                # dataY.append(dataset[i: i+5,0:dataset.shape[1]])
                dataY.append(dataset[i,0:dataset.shape[1]])
            else:
                break
    return np.array(dataX),np.array(dataY)

dfdate,dflabel=createXY(df,10)
print(dfdate.shape)
print(dflabel.shape)

# 构建模型
def build_model(optimizer):
    grid_model = Sequential()
    # 顺序模型，即通过一层层神经网络连接构建深度神经网络。
    grid_model.add(LSTM(50,return_sequences=True,input_shape=(10,3)))
    # grid_model.add(LSTM(50, return_sequences=True, input_shape=(None)))
    grid_model.add(LSTM(50))
    grid_model.add(Dropout(0.2))
    grid_model.add(Dense(3))
    grid_model.compile(loss = 'mse',optimizer = optimizer)
    return grid_model
grid_model = KerasRegressor(build_fn=build_model,verbose=1)
parameters = {'batch_size' : [16,20],
              'epochs' : [8,19],
              'optimizer' : ['adam','Adadelta'] }
grid_search  = GridSearchCV(estimator = grid_model,
                            param_grid = parameters,
                            cv = 2)
grid_search = grid_search.fit(dfdate,dflabel,validation_data=(dfdate,dflabel))
print('最佳参数：',grid_search.best_params_)

# 保存模型训练结果
my_model=grid_search.best_estimator_.model

# 预测
lastn=[]


for i in range(30):
    # 得到lastnn
    lastn=[]
    lastn.append(df[12+i: 22+i, 0:df.shape[1]])
    lastn = np.array(lastn)

    prediction=my_model.predict(lastn)
    # print(lastn.shape)
    # 逆缩放
    prediction=scaler.inverse_transform(prediction)
    print("prediction预测的结果，现有数据往后第",i,"条：\n", prediction)
    print("\nPrediction Shape-",prediction.shape)

    # 将predict放到data里面
    data = data.tolist()
    data.append(prediction.tolist()[0])
    data=np.array(data)

    # 进行缩放
    scaler = MinMaxScaler(feature_range=(0, 1))
    df = scaler.fit_transform(data)
    print('这是data:\n',data)
    # lastnn = lastn[0]
    # lastnn = lastnn.tolist()
    # lastnn.append(prediction.tolist()[0])
    # print('这是lastnn：\n',lastnn)
    # # l_pop = lastnn.pop(0)
    # # print(lastnn, 'eee\n', l_pop)
    # lastn[0] = lastnn

data=pd.DataFrame(data)
data.to_excel('yuceresult.xlsx')
print('预测的结果：\n',lastn)